﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using GeneralLibs;
using Lists;
using Vouchers;
using Excel = Microsoft.Office.Interop.Excel;

namespace KeToanTongHop
{
    public partial class FrmGhiSoLaiCacChungTu : BasicForms.FrmBase
    {
        public FrmGhiSoLaiCacChungTu()
        {
            InitializeComponent();
        }

        private void FrmGhiSoLaiCacChungTu_Load(object sender, EventArgs e)
        {
            if (DesignMode) return;
            rItemGridLookUpEditLoaiChungTu.DataSource = DanhMucLoaiChungTu.Instance.DataView;
            rItemLookUpEditDoiTuongNghiepVu.DataSource = DanhMucDoiTuongNghiepVu.Instance.DataView;
            #region cmbLoaiChungTu
            cmbLoaiChungTu.DataSource = DanhMucLoaiChungTu.Instance.DataView;
            cmbLoaiChungTu.DisplayColumn = "Ten";
            cmbLoaiChungTu.ValueColumn = "ID";
            cmbLoaiChungTu.AddVisibleColumn("Ma", "Mã");
            cmbLoaiChungTu.AddVisibleColumn("Ten", "Tên");
            #endregion
            cmbLoaiChungTu.EditValue = Guid.Empty;

            cmbKyBaoCao.SelectedIndex = -1;
            cmbKyBaoCao.SelectedText = "Tùy chọn";
        }

        DanhSachChungTu _DanhSachChungTu = new DanhSachChungTu();

        protected virtual void cmbKyBaoCao_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                BasicForms.FrmThamSoBaoCao.ThietLapKhoangThoiGianBaoCao(cmbKyBaoCao.Text, cmbKyBaoCao, dtNgayBatDau, dtNgayKetThuc);
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void btnGhiSoLai_Click(object sender, EventArgs e)
        {
            BasicForms.FrmProgressBar.StartShowProgress();

            SqlConnection con = new SqlConnection(GeneralLibs.LocalSettings.ConnectString);
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();

                int count = 0;
                foreach (ChungTu chungTu in _DanhSachChungTu)
                {
                    BasicForms.FrmProgressBar.Status = string.Format("Đã xử lý {0}/{1}", count, _DanhSachChungTu.Count);
                    count++;

                    if (!chungTu.DinhKhoan) continue;

                    LoaiChungTu loaiChungTu = DanhMucLoaiChungTu.Instance.GetByID(chungTu.LoaiChungTuID);

                    BasicForms.FrmEditChungTu frm = null;
                    switch (loaiChungTu.Ma)
                    {
                        case "PhieuThu":
                            frm = new QuanLyQuy.FrmEditPhieuThu(chungTu);
                            break;
                        case "PhieuChi":
                            frm = new QuanLyQuy.FrmEditPhieuChi(chungTu);
                            break;
                        case "GiayBaoCo":
                            frm = new QuanLyQuy.FrmEditGiayBaoCo(chungTu);
                            break;
                        case "GiayBaoNo":
                            frm = new QuanLyQuy.FrmEditGiayBaoNo(chungTu);
                            break;

                        case "PhieuNhapKho":
                            frm = new QuanLyKho.FrmEditPhieuNhapKho(chungTu);
                            break;
                        case "PhieuXuatKho":
                            frm = new QuanLyKho.FrmEditPhieuXuatKho(chungTu);
                            break;
                        case "PhieuChuyenKho":
                            frm = new QuanLyKho.FrmEditPhieuChuyenKho(chungTu);
                            break;

                        case "HoaDonMuaHang":
                            frm = new MuaHang.FrmEditHoaDonMuaHang(chungTu);
                            break;
                        case "HangMuaTraLai":
                            frm = new MuaHang.FrmEditHangMuaTraLai(chungTu);
                            break;

                        case "HoaDonBanHang":
                            frm = new BanHang.FrmEditHoaDonBanHang(chungTu);
                            break;
                        case "HangBanTraLai":
                            frm = new BanHang.FrmEditHangBanTraLai(chungTu);
                            break;

                        case "PhieuKeToan":
                            frm = new KeToanTongHop.FrmEditPhieuKeToan(chungTu);
                            break;
                        case "PhieuBuTruCongNo":
                            frm = new KeToanTongHop.FrmEditPhieuBuTruCongNo(chungTu);
                            break;
                    }

                    if (frm != null)
                    {
                        frm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
                        frm.WindowState = FormWindowState.Normal;
                        frm.ShowInTaskbar = false;
                        frm.Width = 0;
                        frm.Height = 0;
                        frm.Location = new Point(-10000, -10000);

                        frm.Show();
                        frm.Visible = false;

                        try 
                        {
                            if(!BasicForms.FrmProgressBar.ShowProgressBar)
                                BasicForms.FrmProgressBar.StartShowProgress();

                            BasicForms.FrmProgressBar.Status = string.Format("Đã xử lý {0}/{1}", count, _DanhSachChungTu.Count);

                            frm.ReSaveLedger();
                        }
                        catch (Exception ex)
                        {
                            CustomControls.MessageBoxEx.Show(ex.Message, 4000);
                        }

                        frm.Close();
                    }
                    else
                    {
                        chungTu.LoadKhoanMuc(cmd);
                        chungTu.LoadDanhSachChungTuPhuThuoc(cmd);
                        chungTu.DinhKhoanButToan(cmd);
                    }
                }
                BasicForms.FrmProgressBar.FinishShowProgress();

                MessageBox.Show("Ghi sổ lại thành công");
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
            finally
            {
                con.Close();
                BasicForms.FrmProgressBar.FinishShowProgress();
            }
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            BasicForms.FrmProgressBar.StartShowProgress();

            SqlConnection con = new SqlConnection(GeneralLibs.LocalSettings.ConnectString);
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();

                DieuKienTimKiemChungTu dkTimKiem = new DieuKienTimKiemChungTu();
                dkTimKiem.TuNgay = new GeneralLibs.NullableDate(dtNgayBatDau.DateTime);
                dkTimKiem.DenNgay = new GeneralLibs.NullableDate(dtNgayKetThuc.DateTime);

                dkTimKiem.DieuKienKhac = string.Format("DinhKhoan = 1 AND GhiSo = 1");
                if ((Guid)cmbLoaiChungTu.EditValue != Guid.Empty)
                    dkTimKiem.DieuKienKhac += string.Format(" AND LoaiChungTuID = '{0}'", (Guid)cmbLoaiChungTu.EditValue);

                _DanhSachChungTu.LoadFromDB(dkTimKiem.BuildSqlStatement(0, 0));

                dsGhiSoLaiCacChungTu.ChungTu.Clear();
                dsGhiSoLaiCacChungTu.ChungTu.Merge(_DanhSachChungTu.DataTable);
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
            finally
            {
                con.Close();
            }
            BasicForms.FrmProgressBar.FinishShowProgress();
        }
        private void btnLoadChungTuFromExcel_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog openFileDialog = new OpenFileDialog();
                openFileDialog.Filter = "Excel file|*.xlsx;*.xls";
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    BasicForms.FrmProgressBar.StartShowProgress();

                    string path = openFileDialog.FileName;
                    Excel.ApplicationClass app = new Microsoft.Office.Interop.Excel.ApplicationClass();
                    Excel.Workbook workBook = app.Workbooks.Open(path, 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t",
                                    false, false, 0, true, 1, 0);
                    Excel.Worksheet workSheet = (Excel.Worksheet)workBook.ActiveSheet;
                    Excel.Range range = workSheet.UsedRange;

                    if (range.Columns.Count >= 1)
                    {
                        string soChungTuCondition = "So IN ("; //Điều kiện 

                        Hashtable htChungTuKhongHopLe = new Hashtable();
                        for (int rowIndex = 1; rowIndex <= range.Rows.Count; rowIndex++)
                        {
                            try
                            {
                                //Đọc từ cột 1
                                soChungTuCondition += string.Format("N'{0}'", (range.Cells[rowIndex, 1] as Excel.Range).Text.ToString().Trim()) + ", ";
                            }
                            catch (Exception ex)
                            {
                                htChungTuKhongHopLe.Add(rowIndex, (range.Cells[rowIndex, 1] as Excel.Range).Text.ToString().Trim());
                            }
                        }

                        if (soChungTuCondition.EndsWith(", "))
                            soChungTuCondition = soChungTuCondition.Substring(0, soChungTuCondition.Length - 2) + ")";

                        DieuKienTimKiemChungTu dkTimKiem = new DieuKienTimKiemChungTu();

                        dkTimKiem.DieuKienKhac = string.Format("DinhKhoan = 1 AND GhiSo = 1 AND {0}", soChungTuCondition);

                        _DanhSachChungTu.LoadFromDB(dkTimKiem.BuildSqlStatement(0, 0));

                        dsGhiSoLaiCacChungTu.ChungTu.Clear();
                        dsGhiSoLaiCacChungTu.ChungTu.Merge(_DanhSachChungTu.DataTable);

                    }
                    workBook.Close(false, path, true);

                    BasicForms.FrmProgressBar.FinishShowProgress();
                }
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void cmbLoaiChungTu_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete) cmbLoaiChungTu.EditValue = Guid.Empty;
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
